<template>
  <div class="labelStaff content">
    <el-form
      ref="form"
      :model="model"
      :rules="rules"
      label-width="130px"
      label-suffix="："
    >
      <div style="display: flex">
        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker
            v-model="model.beginDate"
            type="date"
            placeholder="开始时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 272px"
            clearable
            :disabled="isEdit && isStopOrOn"
            :disabled-date="(d) => dayjs(d).isAfter(dayjs(model.endDate))"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker
            v-model="model.endDate"
            type="date"
            placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 272px"
            clearable
            :disabled="isEdit && isStopOrOn"
            :disabled-date="(d) => dayjs(d).isBefore(dayjs(model.beginDate))"
          ></el-date-picker>
        </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="任务方式" prop="pubMethod">
          <el-select
            v-model="model.pubMethod"
            placeholder="任务方式"
            style="width: 272px"
            @change="changePubMethod"
            :disabled="isEdit && isStopOrOn"
          >
            <el-option
              v-for="item in pubMethodOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务分配方式" prop="assignMethod">
          <el-select
            v-model="model.assignMethod"
            placeholder="任务分配方式"
            style="width: 272px"
            :disabled="isEdit && isStopOrOn"
          >
            <el-option
              v-for="item in assignMethodOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="交叉次数"
          prop="crossNum"
          v-if="model.assignMethod == 2"
          :rules="[
            {
              required: model.assignMethod == 2,
              message: '请输入交叉次数',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input
            :disabled="isEdit && isStopOrOn"
            v-model.number="model.crossNum"
            placeholder="交叉次数"
            style="width: 272px"
          ></el-input>
        </el-form-item>
      </div>

      <div v-show="model.pubMethod == 1" style="display: flex">
        <el-form-item label="可参与人数">
          <el-input
            :disabled="isEdit && isStopOrOn"
            :value="totalUserNumText"
            style="width: 272px"
            disabled
          ></el-input>
        </el-form-item>
      </div>
      <div
        v-show="model.pubMethod == 2"
        style="display: flex"
        v-for="(item, index) in model.annoUserList"
        :key="index"
      >
        <el-form-item
          label="标注单位"
          :prop="'annoUserList.' + index + '.companyId'"
          :rules="[
            {
              required: model.pubMethod == 2,
              message: '标注单位',
              trigger: ['change'],
            },
            {
              trigger: ['change'],
              validator: validateCompany,
            },
          ]"
        >
          <el-select
            v-model="item.companyId"
            placeholder="标注单位"
            style="width: 272px"
            @change="changeAnnoUser(index, item.companyId)"
          >
            <el-option
              v-for="subItem in item.companyIdOptions"
              :key="subItem.id"
              :label="subItem.name"
              :value="subItem.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="可选名单"
          :prop="'annoUserList.' + index + '.userIdList'"
          :rules="[
            {
              required: model.pubMethod == 2,
              message: '可选名单',
              trigger: ['change'],
            },
          ]"
        >
          <el-select
            v-model="item.userIdList"
            placeholder="可选名单"
            style="width: 272px"
            multiple
            collapse-tags
          >
            <el-option
              v-for="subItem2 in item.userListOptions"
              :key="subItem2.id"
              :label="subItem2.userName"
              :value="subItem2.id"
            >
            </el-option>
          </el-select>
          <!-- <el-button>{{ item.userIdList.length || 0}}人</el-button> -->
        </el-form-item>
        <el-form-item
          v-show="index != 0"
          label=""
          label-width="0px"
          style="margin-left: 24px"
        >
          <el-icon @click="del(index)"><Delete /></el-icon>
        </el-form-item>
      </div>
      <el-form-item label="" v-show="model.pubMethod == 2">
        <el-button @click="add" :icon="Plus" style="width: 272px">添加标注单位</el-button>
      </el-form-item>

      <el-form-item label="任务备注">
        <el-input
          style="width: 900px"
          type="textarea"
          :rows="7"
          placeholder="任务备注"
          v-model="model.remark"
        >
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import bus from "@/utils/bus";
import { PageType, taskStatus, ProjectType, Step } from "@/utils/emun";
import { getUrlParams, open } from "@/utils/window";
import { setDraft, getDraft } from "@/utils/draft";
import moment from "moment";
import useLoading from "@/hooks/loading";

import {
  getCompanylist,
  userSearch,
  taskCreate,
  taskUpdate,
  annoTask,
} from "@/api/projectDetail/projectDetail";
import { ElLoading } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";

export default {
  components: {},
  data() {
    const { projectId, projectStatus } = getUrlParams();
    const validateEndDate = (rule, endData, callback) => {
      const { beginDate } = this.model;
      if (!endData) {
        return callback(new Error("请选择结束时间"));
      }
      if (beginDate && endData) {
        const isBefore = moment(beginDate).isSameOrBefore(endData);
        if (isBefore) {
          callback();
        } else {
          return callback(new Error("结束时间必须在开始时间之后"));
        }
      }
      callback();
    };
    const validateCrossNum = (rule, crossNum, callback) => {
      const { assignMethod } = this.model;
      if (assignMethod != 2) {
        return callback();
      }
      const isValid = crossNum >= 2 && crossNum < 50;
      if (isValid) {
        callback();
      } else {
        return callback(new Error("请输入大于等于2小于50的整数"));
      }
    };
    return {
      Plus,
      Delete,
      projectStatus: projectStatus ? Number(projectStatus) : null,
      pageType: projectId && projectId.length === 16 ? PageType.create : PageType.edit,
      projectId,
      model: {
        beginDate: null, //  开始时间
        endDate: null, //  结束时间
        remark: null, //  备注
        pubMethod: null, //  任务方式  Integer Y 1-开放式 2-承包式
        assignMethod: null, //  分配方式  1-抢单式 2-交叉式
        crossNum: 2, //  交叉次数
        totalUserNum: 0, //  可参与人总数
        annoUserList: [],
      },
      rules: {
        beginDate: [{ required: true, message: "请选择开始时间", trigger: ["blur"] }],
        endDate: [
          // { required: true, message: '结束时间', trigger: ['blur'] },
          { required: true, validator: validateEndDate, trigger: ["blur"] },
        ],
        pubMethod: [{ required: true, message: "请选择任务方式", trigger: ["blur"] }],
        assignMethod: [
          { required: true, message: "请选择任务分配方式", trigger: ["blur"] },
        ],
        crossNum: [{ validator: validateCrossNum, trigger: ["blur"] }],
      },
      pubMethodOptions: [
        { value: 1, name: "开放式" },
        { value: 2, name: "承包式" },
      ],
      assignMethodOptions: [
        { value: 1, name: "抢单式" },
        { value: 2, name: "交叉式" },
      ],
    };
  },
  computed: {
    isCreate() {
      return this.pageType === PageType.create;
    },
    isEdit() {
      return this.pageType === PageType.edit;
    },
    isView() {
      return this.pageType === PageType.view;
    },
    // 进行中
    isOn() {
      return taskStatus.way === this.projectStatus;
    },
    // 未发布
    isOff() {
      return taskStatus.off === this.projectStatus;
    },
    // 已完成
    isFinish() {
      return taskStatus.finish === this.projectStatus;
    },
    // 已终结
    isStop() {
      return taskStatus.end === this.projectStatus;
    },
    // 进行中 或者 已终结
    isStopOrOn() {
      return this.isOn || this.isStop;
    },
    totalUserNumText() {
      return `共${this.model.totalUserNum}人可参与标注`;
    },
  },
  watch: {
    model: {
      deep: true,
      handler(model) {
        setDraft(this.projectId, "annoUserSetting", model);
      },
    },
  },
  async created() {
    this.initData();
    bus.off("labelProject." + Step.labelStaff);
    bus.on("labelProject." + Step.labelStaff, () => {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submit();
        }
      });
    });

    bus.off(`labelProject.editSave.${Step.labelStaff}`);
    bus.on(`labelProject.editSave.${Step.labelStaff}`, () => {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.update();
        }
      });
    });
  },
  methods: {
    dayjs,
    async submit() {
      const model = this.getModel();
      const res = await taskCreate(model);
      Message.success("已提交");
      bus.emit(`labelProject.goCreated`, {
        projectId: res.data?.id,
      });
    },
    async update() {
      const loadingIns = ElLoading.service({ fullscreen: true });
      const model = this.getModel();
      model.id = this.projectId;
      const res = await taskUpdate(model);
      loadingIns.close();
      Message.success("已提交");
      bus.emit(`labelProject.goCreated`);
    },
    async changePubMethod() {
      const res = await userSearch({
        pageSize: 10000,
        status: 1,
      });
      const totalUserNum = res.data.list.length;
      this.model = {
        ...this.model,
        totalUserNum,
      };
    },
    async changeAnnoUser(index, companyId) {
      const userIdList = await this.getUserListOptions(companyId);
      const annoUserList = JSON.parse(JSON.stringify(this.model.annoUserList));
      annoUserList[index] = {
        ...annoUserList[index],
        userIdList: userIdList.map((item) => item.id),
        userListOptions: userIdList,
      };
      this.model = {
        ...this.model,
        annoUserList,
      };
    },
    async getUserListOptions(companyId) {
      const res = await userSearch({
        pageSize: 10000,
        companyId,
        status: 1,
      });
      return res.data.list;
    },
    nextStep() {
      bus.off(`labelProject.${Step.baseProjectInfo}`);
      bus.on(`labelProject.${Step.baseProjectInfo}`, async () => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const model = this.getModel();
            setDraft(this.projectId, "baseInfo", model);
            bus.emit("labelProject.valid");
          }
        });
      });
    },
    del(index) {
      this.model.annoUserList.splice(index, 1);
    },
    async add() {
      const list = await this.companylist();
      this.model.annoUserList.push({
        companyId: null, //标注单位
        companyIdOptions: JSON.parse(JSON.stringify(list || [])),
        userIdList: [], //
        userListOptions: [],
        userListLength: 0,
      });
    },
    getModel() {
      const { projectConfigModel, seriesFcListTableData, dataSetting } = getDraft(
        this.projectId
      ) || {
        projectConfigModel: {},
        seriesFcListTableData: [],
        dataSetting: [],
      };
      // 基本信息
      const basicSetting = {
        name: projectConfigModel.name, //任务名称
        department: projectConfigModel.department, //科室
        label: projectConfigModel.label, //任务标签
        target: projectConfigModel.target, //任务目标
        uses: projectConfigModel.uses, //任务用途
        discardCode: projectConfigModel.discardCode
          ? projectConfigModel.discardCode.join(",")
          : "", // 废片原因 以,分隔
      };
      // 标注信息
      const annoSetting = {
        defaultWindow: projectConfigModel.defaultWindow, //默认窗宽窗位
        findings: projectConfigModel.findings, //是否展示检查所见
        diagnosis: projectConfigModel.diagnosis, //是否展示诊断所得
        showYay: projectConfigModel.showYay, //是否需要阴阳性
        showReport: projectConfigModel.showReport, //是否需要图文报告
        imageLayout: projectConfigModel.imageLayout, //布局
        seriesFcList: (seriesFcListTableData || []).map((item) => {
          return {
            fcId: item.id || item.fcId,
            required: item.required,
          };
        }),
        lesionList: (projectConfigModel?.lesionList || []).map((item) => {
          return {
            lesionValue: item.lesionValue, //病灶编码
            color: item.color, //颜色
            toolValueList: item.toolValueList, //工具编码列表
            imageFcList: (item.imageFcListData || []).map((subItem) => {
              return {
                fcId: subItem.id || subItem.fcId,
                required: subItem.required,
              };
            }),
            bizType: item.bizType,
          };
        }),
      };

      // 添加数据
      const _dataSetting = {
        annoSeriesList: (dataSetting || []).map((item) => {
          return {
            seriesUid: item.seriesUid, //序列号
            auxSeriesList: item.auxSeriesList || [], //辅助/配准序列号
            annoAreaList: item.annoAreaList || [], //大图标注区域
          };
        }),
      };
      const model = {
        basicSetting,
        annoSetting,
        dataSetting: _dataSetting,
        annoUserSetting: this.getAnnoUserSettingModel(),
      };
      return model;
    },
    getAnnoUserSettingModel() {
      const { annoUserSetting } = getDraft(this.projectId) || {
        annoUserSetting: {},
      };
      const annoUserList =
        annoUserSetting.pubMethod == 2
          ? (annoUserSetting.annoUserList || []).map((item) => {
              return {
                companyId: item.companyId,
                userIdList: item.userIdList,
              };
            })
          : [];
      const _annoUserSetting = {
        beginDate: annoUserSetting.beginDate,
        endDate: annoUserSetting.endDate,
        remark: annoUserSetting.remark,
        pubMethod: annoUserSetting.pubMethod,
        assignMethod: annoUserSetting.assignMethod,
        crossNum:
          annoUserSetting.assignMethod == 1 ? 1 : Number(annoUserSetting.crossNum),
        annoUserList,
      };
      return _annoUserSetting;
    },
    async initData() {
      if (this.isCreate) {
        const createModel = getDraft(this.projectId, "annoUserSetting");
        if (createModel) {
          this.model = createModel;
        }
      }
      if (this.isEdit) {
        const res = (await annoTask(this.projectId)).data;
        const draftModel = getDraft(this.projectId, "annoUserSetting");
        const editModel = draftModel || res.annoUserInfo;
        const annoUserList = editModel.annoUserList || [];
        const list = await this.companylist();
        const ids = annoUserList.map((item) => item.company?.id || item.companyId);
        for (let i = 0; i < ids.length; i++) {
          const userListOptions = await this.getUserListOptions(ids[i]);
          annoUserList[i].userListOptions = userListOptions;
        }
        this.model = {
          ...editModel,
          beginDate: editModel.beginDate
            ? moment(editModel.beginDate).format("YYYY-MM-DD")
            : null,
          endDate: editModel.endDate
            ? moment(editModel.endDate).format("YYYY-MM-DD")
            : null,
          annoUserList: annoUserList.map((item) => {
            return {
              ...item,
              userIdList: (item.userList || []).map((subItem) => subItem.id),
              companyId: item.company?.id || item.companyId,
              companyIdOptions: JSON.parse(JSON.stringify(list || [])),
              userListLength: 0,
            };
          }),
        };
      }
      if (!this.model.annoUserList?.length) {
        this.add();
      }
    },
    async companylist() {
      const res = await getCompanylist({
        status: 1,
      });
      return res.data;
    },
    validateCompany(rule, companyId, callback) {
      const { annoUserList } = this.model;
      //验证重复
      const repeatArr = annoUserList.filter((item) => item.companyId === companyId);
      if (repeatArr.length > 1) {
        return callback(new Error("标注单位重复"));
      } else {
        callback();
      }
    },
  },
};
</script>

<style lang="less">
@basicColor: #448e97;
.base-project-info {
  position: relative;
  padding: 20px 20px 60px;
  color: #333;
  background: #fff;
  .task-name-item {
    input.el-input__inner {
      border: none;
      border-bottom: 1px solid #dcdfe6;
      background-color: #fff;
      color: #333;
    }
  }
  .header-title {
    font-size: 16px;
    margin-bottom: 20px;
    padding-left: 10px;
    .title {
      margin-bottom: 10px;
    }
  }
  .el-select {
    width: 100%;
  }

  .doc {
    .el-form-item__content {
      display: flex;
    }
    .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      border-color: #dcdfe6;
      color: #666;
      cursor: not-allowed;
    }
    .el-input {
      // width: 97%;
    }
    .upload-file-series {
      // width: ;
    }
  }

  .el-form-detail {
    .el-button {
      background: rgba(68, 142, 151, 0.1);
      span {
        color: #448e97;
      }
    }
  }
}
</style>
